from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
import win32serviceutil
import win32api, win32con
from pyservice import DjangoService
import os
import sys

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--noreload', action='store_false', dest='use_reloader', default=True,
            help='Tells Django to NOT use the auto-reloader.'),
    )
    help = "Manages a lightweight Web server as a win32 service."
    args = '[optional port number, or ipaddr:port]'

    requires_model_validation = True

    def handle(self, cmd='', *args, **options):
        argv = ['service', cmd,]
        argv.extend(args)
        settings = os.environ['DJANGO_SETTINGS_MODULE']
        DjangoService._svc_name_ += settings
        DjangoService._svc_display_name_ += settings
        if cmd == 'start' or cmd == 'debug':
            print 'PYTHONPATH must be set in the environment.'
            print '  optional arg: port or addr:port (default=8000)'
            if len(args) == 0: argv.append('8000')
            argv.append(settings)
        if cmd == 'install':
            # python service must find django project
            path = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
            if update_pythonpath_env(path):
                print 'PYTHONPATH has been updated in the registry db; Windows should be restarted.'
        win32serviceutil.HandleCommandLine(DjangoService, argv=argv)

def update_pythonpath_env(path):
    env_keyname = "System\\CurrentControlSet\\Control\\Session Manager\\Environment"
    hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                               env_keyname,
                               0, win32con.KEY_QUERY_VALUE)
    try:
        pathes = win32api.RegQueryValueEx(hkey, "PYTHONPATH")[0]
    except Exception, v:
        # let's create PYTHONPATH env variable
        hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                                   env_keyname,
                                   0, win32con.KEY_SET_VALUE)
        win32api.RegSetValueEx(hkey, "PYTHONPATH", 0, win32con.REG_SZ, path);
        return True
    
    # if path is already set, do nothing
    for p in pathes.split(';'):
        if p == path: return False
    
    # let's add path in PYTHONPATH
    pathes = '%s;%s' % (path, pathes)
    hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                               env_keyname,
                               0, win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(hkey, "PYTHONPATH", 0, win32con.REG_SZ, pathes);
    return True
